﻿using System;
using System.Collections.Generic;
using System.Linq;
using DLM.Domain.Model;
using DLM.Domain.Repositories;
using DLM.Infrastructure.UnitOfWork;
using DLM.Infrastructure.Domain;
using Webdiyer.WebControls.Mvc;
using DLM.Domain.DTO;
using DLM.Infrastructure.Logging;

namespace DLM.Data.EF.CodeFirst.Repositories
{
    public class BonusRepository : Repository<Bonus, int>, IBonusRepository
    {

        public BonusRepository(IUnitOfWork unitOfWork)
            : base(unitOfWork)
        { }

        public new System.Collections.IEnumerator GetEnumerator()
        {
            throw new NotImplementedException();
        }

        public Bonus FindByUser(int userID)
        {
            if (userID < 0)
            {
                throw new ArgumentOutOfRangeException("User id");
            }
            return this.ActiveContext.Bonus.FirstOrDefault(b => b.UserID == userID);
        }


        public IEnumerable<Domain.DTO.BonusDTO> FindBonusDTO(int pageIndex, int pageSize)
        {
            var result = from u in this.ActiveContext.User
                         join b in this.ActiveContext.Bonus
                         on u.UserID equals b.UserID
                         select new BonusDTO
                         {
                             AccountName = u.AccountName,
                             BonusID = b.BonusID,
                             CreateDate = b.CreateDate,
                             UpdateDate = b.UpdateDate,
                             UserID = b.UserID,
                             Bonuses = b.Bonuses
                         };
            return result.OrderByDescending(b => b.CreateDate).ToPagedList(pageIndex, pageSize);
        }


        public void BachUpdate(IList<Bonus> list)
        {
            if (list == null)
            {
                throw new ArgumentNullException("List");
            }
            this.ActiveContext.Configuration.AutoDetectChangesEnabled = false;
            foreach (var item in list)
            {
                try
                {
                    var bonus = this.ActiveContext.Bonus.Find(item.BonusID);
                    bonus.Bonuses = bonus.Bonuses + item.Bonuses;
                    bonus.UpdateDate = item.UpdateDate;
                    this.Save(bonus);
                }
                catch (Exception ex)
                {
                    LoggingFactory.GetLogger().Log(ex.Message);
                    
                }
              
            }
            this.ActiveContext.Configuration.AutoDetectChangesEnabled = true;
        }
    }
}
